<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogVisible"
    :title="title"
    width="1000px"
    @close="resetForm('ruleForm')"
  >
    <button-group
      ref="buttonGroup"
      @submitForm="submitForm('ruleForm')"
      @cancel="dialogVisible = false"
    />
    <div class="formTopFont">物料出库单</div>
    <el-row>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库单号" prop="outNo">
              <el-input
                v-model="ruleForm.outNo"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="ruleForm.customerId"
                @change="
                  ruleForm.customerName = customerAllList.find(
                    (item) => item.id === ruleForm.customerId
                  ).customerName
                "
                style="width: 100%"
              >
                <el-option
                  v-for="item in customerAllList"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="outDate">
              <el-date-picker
                v-model="ruleForm.outDate"
                type="date"
                placeholder="选择日期时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库类别" prop="outType">
              <el-input v-model="ruleForm.outType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库人" prop="userId">
              <el-select
                v-model="ruleForm.userId"
                @change="
                  ruleForm.userName = userAllList.find(
                    (item) => item.id === ruleForm.userId
                  ).name
                "
                style="width: 100%"
              >
                <el-option
                  v-for="item in userAllList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                maxlength="200"
                type="textarea"
                rows="3"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-if="obj.id"
        border
        stripe
        height="220px"
        class="tabOver"
        :data="ruleForm.materials"
      >
        <el-table-column prop="materialId" label="物料" align="center">
          <template #default="{ row }"
            >{{ row.materialName
            }}{{
              row.materialCode ? "【" + row.materialCode + "】" : ""
            }}</template
          >
        </el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="wmsName"
          label="库房"
          width="200px"
          align="center"
        />
        <el-table-column
          prop="totalPrice"
          label="总金额"
          width="130px"
          align="center"
        />
        <el-table-column
          prop="outNum"
          label="出库数量"
          align="center"
          width="120px"
        />
        <el-table-column
          prop="outPrice"
          label="出库单价"
          align="center"
          width="120px"
        />
      </el-table>
      <el-table
        v-else
        border
        stripe
        height="220px"
        class="tabOver"
        :data="ruleForm.materials"
      >
        <el-table-column prop="inventoryId" width="280px" align="center">
          <template slot="header">
            <span style="color: #f56c6c">*</span>物料
          </template>
          <template #default="{ row, $index }">
            <el-select
              v-model="row.inventoryId"
              filterable
              size="mini"
              style="width: 100%"
            >
              <el-option
                v-for="item in materialList"
                :key="item.inventoryId"
                :disabled="
                  ruleForm.materials.some(
                    (el) => el.inventoryId === item.inventoryId
                  )
                "
                :value="item.inventoryId"
                :label="item.materialName + '【' + item.materialCode + '】'"
              >
                <!-- option已经禁选 点击事件还是可以触发 disabled对于div没用 所以加了class禁止鼠标点击（yqy 2021-11-25） -->
                <div
                  class="optionBox"
                  :class="
                    ruleForm.materials.some(
                      (el) => el.inventoryId === item.inventoryId
                    ) === true
                      ? 'form-onlyRead'
                      : 'optionBox'
                  "
                  @click="getMaterialInfo($index, item)"
                >
                  <span style="float: left"
                    >{{ item.materialName
                    }}{{
                      item.materialCode ? "【" + item.materialCode + "】" : ""
                    }}</span
                  >
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.wmsName
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="wmsName"
          label="库房"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="price"
          label="库存单价"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="num"
          label="库存数量"
          width="100px"
          align="center"
        />
        <el-table-column prop="outNum" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>出库数量
          </template>
          <template #default="{ row }">
            <el-input-number
              v-model="row.outNum"
              size="mini"
              :controls="false"
              :max="row.num"
              :min="1"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="outPrice" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>出库单价
          </template>
          <template #default="{ row }">
            <el-input-number
              v-model="row.outPrice"
              size="mini"
              :precision="2"
              :controls="false"
              :min="1"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="ruleForm.materials.splice($index, 1)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        v-if="!obj.id"
        style="width: 100%"
        @click="ruleForm.materials.push({ ...basicParams })"
        >添加</el-button
      >
    </el-row>
    <bottom-font
      v-if="title === '编辑'"
      ref="bottomFont"
      :obj-name="ruleForm.userName"
      :rew-name="ruleForm.reviewer"
      :obj-date="ruleForm.outDate"
    />
  </el-dialog>
</template>
<script>
import TreeSelect from "@/components/TreeSelect";
import { timeFormatToString } from "@/utils/function";
import bottomFont from "@/components/BottomFont";
export default {
  components: { TreeSelect, bottomFont },
  props: {
    customerAllList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    wmsListAll: {
      type: Array,
      default: () => {
        return [];
      },
    },
    userAllList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    const checkOutNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/wms/out/verifyNoUnique?no=${value}&id=${this.ruleForm.id || ""}`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("出库单号重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    const params = {
      outNum: "",
      outPrice: "",
      materialId: "",
    };
    return {
      title: "",
      ruleForm: {
        objId: "",
        customerId: "",
        customerName: "",
        outNo: "",
        outDate: timeFormatToString(new Date()).slice(0, 10),
        outType: "",
        userId: "",
        userName: "",
        remark: "", // 描述
        materials: [],
      },
      rules: {
        outNo: [
          { required: true, message: "出库单号不能为空！", trigger: "blur" },
          { validator: checkOutNo, trigger: "blur" },
        ],
        materialId: [
          { required: true, message: "物料不能为空！", trigger: "change" },
        ],
        num: [{ required: true, message: "数量不能为空！", trigger: "blur" }],
        outDate: [
          { required: true, message: "请选择出库日期！", trigger: "change" },
        ],
      },
      dialogVisible: false,
      materialList: [],
      basicParams: params,
      obj: {},
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.obj = row;
      await this.getMaterialAll();
      if (row && row.hasOwnProperty("id")) {
        const res = await this.$axios.post(`/wms/out/detail?id=${row.id}`);
        if (res?.data.code === 200) {
          this.ruleForm = Object.assign({}, res.data.data);
        }
        this.title = "编辑";
      } else {
        this.title = "新增";
      }
      this.dialogVisible = true;
    },
    /* 获取所有物料 */
    async getMaterialAll() {
      const res = await this.$axios.get(`/wms/out/search`);
      if (res?.data.code === 200) {
        this.materialList = res.data.data;
      }
    },
    /** 获取当前选中物料信息 */
    getMaterialInfo(index, item) {
      const list = JSON.parse(JSON.stringify(this.ruleForm.materials));
      const {
        materialName,
        materialId,
        totalPrice,
        materialCode,
        model,
        price,
        unit,
        wmsName,
        num,
        inventoryId,
      } = item;
      list[index] = {
        materialName,
        materialId,
        totalPrice,
        materialCode,
        model,
        price,
        unit,
        wmsName,
        num,
        outPrice: price,
        outNum: num,
        inventoryId,
      };
      setTimeout(() => {
        this.ruleForm.materials = list;
        console.log(this.ruleForm.materials);
        this.$forceUpdate();
      }, 100);
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.ruleForm.materials.length > 0) {
            const hasEmptyList = [];
            this.ruleForm.materials.forEach((item, index) => {
              if (!item.materialId || !item.outPrice || !item.outNum) {
                hasEmptyList.push(index + 1);
              }
            });
            if (hasEmptyList.length) {
              this.$alert(
                `请完善记录，序号：${hasEmptyList
                  .toString()
                  .replace(/,/g, "、")} !`,
                "提示",
                {
                  confirmButtonText: "确认",
                  type: "warning",
                }
              );
            } else {
              // this.ruleForm.objId = this.obj.id
              console.log(this.ruleForm);
              const res = await this.$axios.post(
                "/wms/out/save",
                this.ruleForm
              );
              if (res?.data.code === 200) {
                this.$notify.success("提交成功！");
                this.dialogVisible = false;
                this.$emit("getTableInfo");
              } else {
                this.$notify.error(res.data.msg);
              }
            }
          } else {
            this.$alert(`请至少添加一条物料信息!`, "提示", {
              confirmButtonText: "确认",
              type: "warning",
            });
          }
        }
      });
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm);
    },
  },
};
</script>
<style lang="scss" scoped>
.form-onlyRead {
  pointer-events: none;
}
.optionBox {
  position: relative;
  width: calc(100% + 40px);
  padding: 0 20px;
  left: -20px;
  height: 34px;
}
</style>
